package com.tz.online.order.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tz.online.cart.service.impl.MemoryCart;
import com.tz.online.common.PageBean;
import com.tz.online.entity.Address;
import com.tz.online.entity.Order;
import com.tz.online.entity.OrderItem;
import com.tz.online.entity.OrderStatus;
import com.tz.online.entity.User;
import com.tz.online.order.service.IOrderService;
import com.tz.online.user.service.IUserService;
import com.tz.online.util.BeanFactory;

@WebServlet(urlPatterns = "/permission/order/*")
public class OrderAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8771778492874292298L;
	/** 业务接口 */
	private IOrderService orderService;
	private IUserService userService;

	/** 请求URL资源常量 */
	private static final String _TO_BALANCE = "/balance";// 提交订单
	private static final String _SAVE_ADDRESSAJAX = "/saveAddress";// 保存地址
	private static final String _SAVE_ORDER ="/saveOrder";//保存订单
	private static final String _TO_ORDERLIST = "/myorders";//跳转至订单页面
	
	public OrderAction() {
		super();
		this.orderService = (IOrderService) BeanFactory.getBean("orderService");
		this.userService = (IUserService) BeanFactory.getBean("userService");

	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 送session作用域中取出user对象
		User user = (User) request.getSession().getAttribute("user");
		/** 从session作用域中取出购物车和 */
		MemoryCart shoppingCart = (MemoryCart) request.getSession().getAttribute("shoppingCart");
		/**根据session中取出的user来查找地址集合*/
		List<Address> addresses = userService.getAddressByUser(user);
		// 1.获取 servletpath
		String servletParh = request.getServletPath();
		if (servletParh.equals("/permission/order")) {
			// 获取pathInfo
			String pathInfo = request.getPathInfo();
			// 根据不同的pathInfo来决定不同的处理
			switch (pathInfo) {

			case _TO_BALANCE:
				/** 接收发送过来的参数 */
				String ids = request.getParameter("ids");

				String[] arr = ids.split(":");// 把接收到的ID分开成数组
				/**
				 * 构建一个商品详情的集合，遍历Id数组，通过id查找每个商品详情
				 * 并且将得到的商品详情放入商品详情的集合，并且转发到确认订单的页面
				 */
				List<OrderItem> items = new ArrayList<>();
				for (String id : arr) {
					OrderItem item = shoppingCart.find(Long.valueOf(id));
					items.add(item);
				}
				request.setAttribute("items", items);
				request.setAttribute("address", addresses);
				forward(request, response, true, "/WEB-INF/jsp/order/confirm_order.jsp");
				break;

			case _SAVE_ADDRESSAJAX:
				PrintWriter out = response.getWriter();
				/** 获取页面发送过来的参数信息 */
				/* String baseAddress = request.getParameter("baseAddress"); */
				String province = request.getParameter("province");
				String city = request.getParameter("city");
				String area = request.getParameter("area");
				String baseAddress = province + "," + city + "," + area;
				String detailAddress = request.getParameter("address_detail");
				String reciver = request.getParameter("reciverName");
				String code = request.getParameter("code");
				String tel = request.getParameter("tel");
				String isDefault = request.getParameter("defaultAddress");
				isDefault = isDefault==null?"0":isDefault;
				List<Address> addrs = userService.getAddressByUser(user);
				for(int i =0;i<=addrs.size()-1;i++){
					addrs.get(i).setIsDefault(0);
					userService.updAddress(addrs.get(i));
				}

				try {
					// 创建一个地址对象,并且封装对象
					Address address = new Address();
					address.setCode(code);
					address.setReceiver(reciver);
					address.setDetail(detailAddress);
					address.setPhone(tel);
					address.setAddr(baseAddress);
					address.setIsDefault(Integer.parseInt(isDefault));
					address.setUser(user);
					userService.addAddress(address);

					// 成功返回'1'
					out.print("1");
				} catch (Exception e) {
					// TODO: handle exception
					// 失败返回'0'
					out.print("0");
					e.printStackTrace();
				}
				break;
				
			case _SAVE_ORDER:
			/*	String addressId = request.getParameter("addressId");*/
				/**获取页面传来的参数*/
				String bids = request.getParameter("bids");
				String[] bid = bids.split(":");
				/**封装数据对象*/
				Set<OrderItem> orderItems = new HashSet<>();
				Order order = new Order();
				for(Address add : addresses){
				/*order = new Order();*/
				for(String bookId : bid){
				/*	orderItems = new HashSet<>();*/
					OrderItem orderItem = shoppingCart.find(Long.valueOf(bookId));
					orderItem.setOrder(order);
					orderItems.add(orderItem);
					
				}
				order.setItems(orderItems);
				order.setUser(user);
				order.setCreateDate(new Date());
				order.setOrderNo("TZ"+new Date().getTime());
				order.setOrderStatus(OrderStatus.NO_PAY);
				order.setPhone(user.getTel());
				order.setAddr(add.getAddr());
				order.setReceiver(add.getReceiver());
				}
				/**保存订单*/
				orderService.save(order);
				shoppingCart.clear();
				forward(request, response, false, "/permission/order/myorders");
				break;
			case _TO_ORDERLIST:
				/**接受页面参数*/
				String now = request.getParameter("pageNow");
				String size = request.getParameter("pageSize");
				/**默认当前页为第一页，默认每页显示八条数据*/
				now = now == null?"1":now;
				size = size == null?"8":size;
				/**根据参数获取分页对象*/
				PageBean<Order>  paging =(PageBean<Order>) orderService.queryByPage(user, Integer.parseInt(now),Integer.parseInt(size));
				/**转发到订单列表界面*/
				request.setAttribute("paging", paging);
				forward(request, response, true, "/WEB-INF/jsp/order/orderlist.jsp");
			}
		}
	}

	/***************
	 * 转发或重定向请求
	 * 
	 * @param request
	 * @param response
	 * @param b
	 *            为真，则转换请求，为false,则重定向请求
	 * @param target
	 *            目标资源
	 * @throws IOException
	 * @throws ServletException
	 */
	private void forward(HttpServletRequest request, HttpServletResponse response, boolean b, String target)
			throws ServletException, IOException {
		if (b) {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(target);
			rd.forward(request, response);
			return;
		} else {
			String contextPath = getServletContext().getContextPath();
			response.sendRedirect(contextPath + target);
			return;
		}
	}
}
